package com.tesam;


import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.jb.tesam.TesamController;
import android.jb.utils.Tools;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ht380d4G_jar_demo.R;

public class TesamActivity extends Activity implements OnClickListener {

	private byte[] INFO_CMD ={0x55,(byte)0x80,0x0e,0x00,0x02,0x00,0x00,0x73};
//	private byte[] INFO_CMD ={(byte)0xe9,(byte)0x00,0x02,0x00,0x10,(byte)0xfb,(byte)0xe6};
	
	private int send_again = 0;
	private Button btn_checkSecurityState , btn_checkVersion , btn_3 , btn_4 , btn_5;
	private TextView tv_show;
	private TesamController tEsamController;
	private Context mContext;
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 1001:
				String text = (String)msg.obj;
				tv_show.setText(text);
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tesam);
		
		initView();
	}

	private void initView() {
		btn_checkSecurityState = (Button) findViewById(R.id.btn_checkSecurityState);
		btn_checkSecurityState.setOnClickListener(this);
		tv_show = (TextView) findViewById(R.id.tv_show);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_checkSecurityState:
			sendMessage(INFO_CMD);
			break;

		default:
			break;
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		sendBroadcast(new Intent("ReleaseCom"));
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tEsamController = TesamController.getInstance();

		try {
			int i = tEsamController.Tesam_Open(this);
			if(i != 0){
				Toast.makeText(this, "上电失败", 1000).show();
			}
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			Toast.makeText(this, "Device not found", 1000).show();
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Toast.makeText(this, "Device not found", 1000).show();
			e.printStackTrace();
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (tEsamController != null)
			try {
				tEsamController.Tesam_Close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		sendBroadcast(new Intent("ReLoadCom"));
	}
	
	private void sendMessage(byte[] cmd){
		if (tEsamController != null) {
			byte[] data = tEsamController.Tesam_Write(cmd);
			if(data == null || data.length <= 0){
				send_again = 0;
				Message message = new Message();
				message.what = 1001;
				if (null != data && data.length > 0) {
					message.obj = Tools.bytesToHexString(data);
				} else {
					message.obj = "无数据返回";
				}
				handler.sendMessage(message);
				return;
			}
			byte[] check = checkDataReturn(data);
			if(null != check && check.length >0){
				send_again = 0;
				Message message = new Message();
				message.what = 1001;
				message.obj = Tools.bytesToHexString(check);
				handler.sendMessage(message);
			}else {
				if(send_again < 3){
					sendMessage(cmd);
					send_again++;
				}else {
					send_again = 0;
					Message message = new Message();
					message.what = 1001;
					if (null != data && data.length > 0) {
						message.obj = Tools.bytesToHexString(data);
					} else {
						message.obj = "无数据返回";
					}
					handler.sendMessage(message);
				}
			}
		}
	}
	
	private byte[] checkDataReturn(byte[] data){
		byte[] checkdata = null;
//		byte[] delectdata = delectBytesNull(data);
		byte[] delectdata = data;
		System.out.println("Tesam_Read:"+Tools.bytesToHexString(delectdata));
		for(int i = 0 ; i < delectdata.length ; i++){
			if(delectdata[i] == 0x55){ //接口设备判别状态字，是否为0x55？
				//SW1 SW2 Len1 Len2 DATA LRC2
				if(i + 4 < delectdata.length){
					int lenght = 2 + 2 + ((delectdata[i+3] << 8) + delectdata[i+4]) + 1;
					checkdata = new byte[lenght];
					for(int j = 0; j < checkdata.length ; j++){
						checkdata[j] = delectdata[i+j+1];
					}
					break;
				}
			}
		}
		return checkdata;
	}
	
	/**
	 * 删除byte[] 里面连续为0x00的字段
	 */
	private byte[] delectBytesNull(byte[] buffer) {
		int len = 0;
		if(null != buffer && buffer.length > 0){
			byte[] temp = new byte[buffer.length];
			for (int i = 0; i < buffer.length; i++) {
				if (buffer[i] != 0x00) {
					temp[i] = buffer[i];
					len++;
				}
			}
			if (len != buffer.length) {
				buffer = null;
				buffer = new byte[len];
				System.arraycopy(temp, 0, buffer, 0, buffer.length);
			}
		}
		return buffer;
	}
}
